<template>
  <div>
    <div id="logScrollDiv" style="width: 100%;height: 500px ;overflow-y:scroll;">
      <div :class="message.sender === 'me' ? 'chat-message-me' : 'chat-message-other'"
        v-for="(message, index) in messages"
        :style="{ 'padding-bottom': messages.length - 1 === index ? '2rem' : 'none' }" :key="index">

        <!--            消息头像-->
        <div
          :class="message.sender === 'me' ? 'message-me-asWhole-headPortrait' : 'message-other-asWhole-headPortrait'">
          <img src="/static/img/logo.4eeb8a8e.png" class="examineeFace_logo_style">
        </div>
        <!--    消息-->
        <div :class="message.sender === 'me' ? 'message-me-asWhole-right' : 'message-other-asWhole-right'">
          <!--            消息上面-->
          <div :class="message.sender === 'me' ? 'message-me-asWhole-top' : 'message-other-asWhole-top'">
            {{ message.sender === 'me' ? '我' : '客服' }}
          </div>
          <!--          消息内容-->
          <div :class="message.sender === 'me' ? 'message-me' : 'message-other'">
            <!-- <article class="markdown-body" v-html="result"></article> -->
            <markdown :source="message.content" v-highlight v-copys></markdown>
            <!-- <div v-if="extractSQL(message.content).length>0">
              <input type="button" value="展示Josn" @click="getJsonCmd(message.content)" />
              <input type="button" value="生成excel" @click="getExcleCmd(message.content)" />
            </div> -->
          </div>
        </div>
      </div>

      <div v-show="showStream" class="chat-message-other">
        <!--消息头像-->
        <div class="message-other-asWhole-headPortrait">
          <img src="/static/img/logo.4eeb8a8e.png" class="examineeFace_logo_style">
        </div>

        <div ckass="'message-other-asWhole-right">
          <!--            消息上面-->
          <div class="message-other-asWhole-top">
            客服
          </div>
          <!--          消息内容-->
          <div class="message-other">

            <markdown :source="AiMsg" v-highlight></markdown>
<!--            <textarea v-model="AiMsg"></textarea>-->
          </div>
        </div>

      </div>

    </div>
    <div>
      <hr>
    </div>
    <div style="display: flex;">
      <div style="width: 80%;padding: 20px;">
        <textarea style="width: 100%;height: 60px;" v-model="msg" placeholder="请输入内容"></textarea>
      </div>
      <div style="width: 20%;padding: 20px;">
        <button @click="sendMsg()" type="button" class="btn"
          style="width: 50px;height: 40px; background-color:#0eb1ff;border:1px solid white;">发送</button>
      </div>
    </div>


  </div>
</template>

<script>
// import { getCodeImg } from "@/api/login";
// import Cookies from "js-cookie";
// import { encrypt, decrypt } from '@/utils/jsencrypt'
import { send, getmessages, sendImg, sendFlux, testSQL, getJson, getExcel } from "@/api/AI/ai";
// 导包
import Markdown from "vue-markdown";
import { v4 as uuidv4 } from 'uuid';
export default {
  name: "Login",
  data() {
    return {
      messages: [
        { sender: 'me', content: '你好！' },

      ],
      msg: '',
      uid: '',
      path: "ws://127.0.0.1:8010/websocket",
      socket: "",
      AiMsg: "助手正在组织语言，请稍等...",
      showStream: false,
      intCount:0
    };
  },
  // 引入组件
  components: { Markdown },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    // this.getCode();
    // this.getCookie();
    this.getMessages();
    let randomUuid = uuidv4();
    this.uid = randomUuid;
  },
  mounted() {
    this.toBottom();
    // this.initWebSocket();
    this.init()
  },
  destroyed() {
    // 销毁监听
    this.socket.onclose = this.close
  },
  methods: {
    init: function () {
      if (typeof (WebSocket) === "undefined") {
        alert("您的浏览器不支持socket")
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },
    open: function () {
      console.log("socket连接成功");
      this.send(this.uid)
    },
    error: function () {
      console.log("连接错误")
    },
    getMessage: function (msg) {
      this.intCount=this.intCount+1;
      setTimeout(()=>{
        this.AiMsg = msg.data;
      },this.intCount*100)
      // this.AiMsg = msg.data;
      this.toBottom();
      console.log(msg.data)
    },
    // 发送消息给被连接的服务端
    send: function (params) {
      this.socket.send(params)
    },
    close: function () {
      console.log("socket已经关闭")
    },
    getMessages() {
      this.loading = true;
      var data = {}
      var that = this;
      getmessages(data).then(response => {
        that.messages = [];
        console.log(response)
        var datafor = response.data;
        for (var i = 0; i < datafor.length; i++) {
          // console.log(datafor[i].content)
          if (datafor[i].role == 'user') {
            that.messages.push({ sender: 'me', content: datafor[i].content });
          } else {
            that.messages.push({ sender: 'other', content: datafor[i].content });
          }
        }

        that.loading = false;
        that.toBottom();
      });
    },
    sendMsg() {
      if(this.msg==''){
        return
      }
      this.intCount=0;
      this.AiMsg = "助手正在组织语言，请稍等...";
      var that = this;
      this.messages.push({ sender: 'me', content: this.msg });
      this.showStream = true;
      //that.messages.push({ sender: 'other', content: this.AiMsg });
      this.toBottom();
      var data = {
        uid: this.uid,
        text: this.msg
      }

      this.msg = ""
      sendFlux(data).then(response => {
        // console.log(response)
        //var jsontext=JSON.parse(response.msg) ;
        //console.log(jsontext)
        this.showStream = false;
        that.messages.push({ sender: 'other', content: response.msg });
        // this.areainfoList = response.rows;
        // this.total = response.total;
        that.loading = false;
        that.toBottom();
      });

    },
    sendSqlMsg() {
      this.AiMsg = "助手正在组织语言，请稍等...";
      var that = this;
      this.messages.push({ sender: 'me', content: this.msg });
      this.showStream = true;
      //that.messages.push({ sender: 'other', content: this.AiMsg });
      this.toBottom();
      var data = {
        uid: this.uid,
        text: this.msg
      }

      this.msg = ""
      testSQL(data).then(response => {
        console.log(response)
        //var jsontext=JSON.parse(response.msg) ;
        //console.log(jsontext)
        this.showStream = false;
        that.messages.push({ sender: 'other', content: response.msg });
        // this.areainfoList = response.rows;
        // this.total = response.total;
        that.loading = false;
        that.toBottom();
      });

    },
    getJsonCmd(str) {
      var sql=this.extractSQL(str);
      this.AiMsg = "助手正在组织语言，请稍等...";
      var that = this;
      //this.messages.push({ sender: 'me', content: this.msg });
      this.showStream = true;

      this.toBottom();
      var data = {
        uid: this.uid,
        text: sql[0]
      }

      this.msg = ""
      getJson(data).then(response => {
        console.log(response)

        this.showStream = false;
        that.messages.push({ sender: 'other', content: response.msg });

        that.loading = false;
        that.toBottom();
      });

    },
    getExcleCmd(str) {
      var sql=this.extractSQL(str);
      this.AiMsg = "助手正在组织语言，请稍等...";
      var that = this;
      //this.messages.push({ sender: 'me', content: this.msg });
      this.showStream = true;
      //that.messages.push({ sender: 'other', content: this.AiMsg });
      this.toBottom();
      var data = {
        uid: this.uid,
        text: sql[0]
      }

      this.msg = ""
      getExcel(data).then(response => {
        console.log(response)
        //var jsontext=JSON.parse(response.msg) ;
        //console.log(jsontext)
        this.showStream = false;
        that.messages.push({ sender: 'other', content: response.msg });
        window.open(response.msg, '_blank');
        // this.areainfoList = response.rows;
        // this.total = response.total;
        that.loading = false;
        that.toBottom();
      });

    },
    toBottom() {
      // 获取下拉div元素
      const div = document.getElementById('logScrollDiv')
      this.$nextTick(function () {
        div.scrollTop = div.scrollHeight
      })
    },
    extractSQLStatements(text) {
      const sqlStatements = [];
      // 定义SQL语句的正则表达式模式
      const sqlPattern = /(?:;|^)\s*(.*?)(?:;|$)/gs;
      let match;

      // 使用正则表达式查找匹配的SQL语句
      while ((match = sqlPattern.exec(text)) !== null) {
        // 将匹配到的SQL语句添加到数组中
        sqlStatements.push(match[1].trim());
      }

      return sqlStatements;
    },
    extractSQL(text) {
      var sqls = [];

      text = text.replaceAll(/[\r\n]/g, " ");

      var start = text.indexOf('```sql');
      var end = text.indexOf('``` ');
      var str = text.substr(start, (end - start));
      if(str.indexOf("select")!=-1||str.indexOf("SELECT")!=-1){
        sqls.push(str.replaceAll("```sql", ""));
      }

      return sqls;

    }

  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.chat-message-other {
  /*background-color: red;*/
  display: flex;
  padding-left: 1rem;
  padding-top: 1rem;
}

.chat-message-me {
  /*background-color: red;*/
  display: flex;
  padding-right: 1rem;
  padding-top: 1rem;
  flex-direction: row-reverse;
  /* 将子div的顺序反转 */

}

.message-me-asWhole-headPortrait {
  padding: 3px;
}

.message-other-asWhole-headPortrait {
  padding: 3px;
}

.message-me-asWhole-right {
  display: flex;
  flex-direction: column;
  /* 设置子元素垂直排列 */
  margin-left: 0.1rem;
}

.message-other-asWhole-right {
  display: flex;
  flex-direction: column;
  /* 设置子元素垂直排列 */
  margin-left: 0.1rem;
}

.message-me-asWhole-top {
  padding: 3px;
  /* font-size: 12px; */
  font-family: 微软雅黑;
  padding: 3px;
  color: rgba(134, 144, 156, 1);
  text-align: right;
}

.message-other-asWhole-top {
  padding: 3px;
  /* font-size: 12px; */
  font-family: 微软雅黑;
  padding: 3px;
  color: rgba(134, 144, 156, 1);
}

.message-me {
  background-color: ghostwhite;
  // max-width: 80%;
  // word-wrap: break-word;
  // /* 处理英文单词换行 */
  // word-break: break-all;
  // /* 处理中文换行 */
  // display: inline-block;
  // /*将div元素转换为行内块元素*/
  // width: auto;
  /* 宽度根据文本宽度自动调正*/
  padding: 6px 12px;
  border-radius: 4px;
  //border: 1px solid rgba(134, 144, 156, 1);
}

.message-other {
  background-color:ghostwhite;
  // max-width: 80%;
  // word-wrap: break-word;
  // /* 处理英文单词换行 */
  // word-break: break-all;
  // /* 处理中文换行 */
  // display: inline-block;
  // /*将div元素转换为行内块元素*/
  // width: auto;
  /* 宽度根据文本宽度自动调正*/
  padding: 6px 12px;
  border-radius: 4px;
  //border: 1px solid rgba(134, 144, 156, 1);
}


.examineeFace_logo_style {
  width: 30px;
}
</style>
